package com.dog.modules.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dog.framework.mybatis.service.impl.BaseServiceImpl;
import com.dog.modules.system.domain.SysUserPost;
import com.dog.modules.system.mapper.SysUserPostMapper;
import com.dog.modules.system.service.SysUserPostService;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liuxk
 * @description 针对表【sys_user_post(用户岗位关系)】的数据库操作Service实现
 * @createDate 2024-01-30 14:47:30
 */
@Service
public class SysUserPostServiceImpl extends BaseServiceImpl<SysUserPostMapper, SysUserPost> implements SysUserPostService {

    @Override
    public void saveOrUpdate(Long userId, List<Long> postIdList) {
        // 数据库岗位ID列表
        List<Long> dbPostIdList = getPostIdList(userId);

        // 需要新增的岗位ID
        Collection<Long> insertPostIdList = CollUtil.subtract(postIdList, dbPostIdList);
        if (CollUtil.isNotEmpty(insertPostIdList)){
            List<SysUserPost> postList = insertPostIdList.stream().map(postId -> {
                SysUserPost entity = new SysUserPost();
                entity.setUserId(userId);
                entity.setPostId(postId);
                return entity;
            }).collect(Collectors.toList());

            // 批量新增
            saveBatch(postList);
        }

        // 需要删除的岗位ID
        Collection<Long> deletePostIdList = CollUtil.subtract(dbPostIdList, postIdList);
        if (CollUtil.isNotEmpty(deletePostIdList)){
            LambdaQueryWrapper<SysUserPost> queryWrapper = new LambdaQueryWrapper<>();
            remove(queryWrapper.eq(SysUserPost::getUserId, userId).in(SysUserPost::getPostId, deletePostIdList));
        }
    }

    @Override
    public void deleteByPostIdList(List<Long> postIdList) {
        remove(new LambdaQueryWrapper<SysUserPost>().in(SysUserPost::getPostId, postIdList));
    }

    @Override
    public void deleteByUserIdList(List<Long> userIdList) {
        remove(new LambdaQueryWrapper<SysUserPost>().in(SysUserPost::getUserId, userIdList));
    }

    @Override
    public List<Long> getPostIdList(Long userId) {
        return baseMapper.getPostIdList(userId);
    }
}




